/*
 * formdetector - detects forms in a page and fills the class with them
 *
 * Copyright (c) 2008 Varun Kumar Reddy Dodla
 * Licensed under GPL (GPL-LICENSE.txt)
 *
 * $Date: 2008-10-16 
 */

function removeFormNodes() {
	while(formTree.getRootNode().hasChildNodes()) {
		formTree.getRootNode().item(0).remove();
	}
}
function detectForms() {
	removeFormNodes();
	
	log.info('Starting form detection.');
	
	//update the message on the wait box
	Ext.MessageBox.updateText('Detecting forms...');
	
	//get the frame doc
	var iframeDoc = $('#center-iframe').contents()[0];
	
	if(!iframeDoc) {
		showErrorBox('Error', 'Cannot detect forms. Error obtaining the center frame DOM.');
		return false;
	}
	
	//check if forms exist
	if($('form', iframeDoc).length == 0) {
		showErrorBox('Error', 'No forms detected on the page.');
		return false;
	}
	
	//start form detection
	var formRoot = formTree.getRootNode();
	var added = false;
	jQuery.each($('form', iframeDoc), function(index, value) {
			added = true;
			addFormToTree(formRoot, this);
	    });
	
	if(added) {
		formRoot.leaf = false;
		formRoot.expand();
		
		//message
		Ext.MessageBox.alert('Info', 'Forms detection complete.');
	} else {
		showErrorBox('Error', 'No forms found in the page.');
	}
	
	log.info('Done form detection and updated DOM Tree in right panel.');
	
	return true;
}

function addFormToTree(formRoot, form) {
	var formNode = new Ext.tree.TreeNode({
        text: form.name,
        id: form.id,
        leaf: true
	});
	formRoot.appendChild(formNode);
	
	//create child nodes for the form
	var added = false;
	jQuery.each($(':input', form), function(index, value) {
		added = true;
		var nodeName = '[<i>'+ value.type + '</i>] <b>' + value.name + '</b>';
		var childNode = new Ext.tree.TreeNode({
	        text: nodeName,
	        id: value.id,
	        leaf: true
		});
		formNode.appendChild(childNode);
	});
        
	if(added) {
		formNode.leaf = false;
	}
}

